/**
 * @FileName: LoginActivity.java
 * @Package:com.bdtop.dbl.ui.activities.acccount
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.acccount;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.LoginResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: LoginActivity
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 */
public class LoginActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private EditText mUserNameText;
    private EditText mPwdText;

    private CheckBox mRememberPwd;
    private CheckBox mAutoLogin;

    private TextView mFogotPwdView;

    private Button mLoginBtn;
    private Button mRegBtn;

    public static final void launch(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    /*
     * public static final void launch(Context context, String username) {
     * Intent intent = new Intent(context, LoginActivity.class);
     * intent.putExtra(Constants.INTENT_NAME, username);
     * context.startActivity(intent); }
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (Preferences.isRememberPwd(this)) {
            mUserNameText.setText(Preferences.getUserName(this));
            mPwdText.setText(Preferences.getPassword(this));
            mRememberPwd.setChecked(true);
        }

        if (Preferences.isAutoLogin(this)) {
            mAutoLogin.setChecked(true);
            // mLoginBtn.performClick();
        }

    }

    private void initViews() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle(R.string.login_title);
        mTitleBar.setBackShowOrHidden(View.GONE);

        mUserNameText = (EditText) findViewById(R.id.login_name);
        mPwdText = (EditText) findViewById(R.id.login_pwd);

        mRememberPwd = (CheckBox) findViewById(R.id.remember_pwd);
        mAutoLogin = (CheckBox) findViewById(R.id.auto_login);

        mFogotPwdView = (TextView) findViewById(R.id.forgot_pwd);
        mFogotPwdView.setOnClickListener(mOnClickListener);

        mLoginBtn = (Button) findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(mOnClickListener);

        mRegBtn = (Button) findViewById(R.id.reg_btn);
        mRegBtn.setOnClickListener(mOnClickListener);

        mUserNameText.setText(Preferences.getLastLoginUser(this));

        mAutoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if(mAutoLogin.isChecked()){
                    mRememberPwd.setChecked(true);
                }
            }
        });
        
        mRememberPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if(!mRememberPwd.isChecked()){
                    mAutoLogin.setChecked(false);
                }
            }
        });
    }

    private OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn:
                    if (check()) {
                        String phoneNumber = mUserNameText.getText().toString();
                        String password = mPwdText.getText().toString();
                        
                    	// fix: 一次性commit
                        Preferences.setRememberPwd(LoginActivity.this, mRememberPwd.isChecked());
                        Preferences.setAutoLogin(LoginActivity.this, mAutoLogin.isChecked());
//                        Editor editor = Preferences.getPreferences(LoginActivity.this).edit();
//                		editor.putBoolean(Preferences.REMEMBER_PWD,  mRememberPwd.isChecked());
//                		editor.putBoolean(Preferences.AUTO_LOGIN, mAutoLogin.isChecked());
//                		editor.commit();
                        ServerApiFactory.getApiImpl().login(phoneNumber, password,
                                mLoginCallback);
                        showWaitingDialog(R.string.waiting_login, false, true);
                    }
                    break;

                case R.id.reg_btn:
                    RegisterActivity.launch(LoginActivity.this);
                    finish();
                    break;

                case R.id.forgot_pwd:
                    if (mUserNameText.getText().toString().trim().length() == 0) {
                        showToast(R.string.name_null);
                    } else {
                        showWaitingDialog(R.string.waiting_get_code, false, true);
                        ServerApiFactory.getApiImpl().getAuthCode(
                                mUserNameText.getText().toString().trim(), new RequestCallback() {

                                    @Override
                                    public void onSuccess(String rawData, Object response) {
                                        BaseResponse baseResponse = (BaseResponse) response;
                                        if (baseResponse.getStatus()
                                                .equals(Constants.REQUEST_SUCCESS)) {
                                            showToast(getString(R.string.get_code_success));
                                            FindPwdActivity.launch(LoginActivity.this,mUserNameText.getText().toString());
                                        } else {
                                            showToast(getString(R.string.get_code_error));
                                        }
                                        dismissDialog();
                                    }

                                    @Override
                                    public void onError(int statusCode, Throwable e, String rawData) {
                                        if(NetworkUtils.isNetConnect(getApplicationContext())){
                                            showToast(R.string.oper_error);
                                        }else{
                                            showToast(R.string.net_error);
                                             }
                                        dismissDialog();
                                    }
                                });
                    }
                    break;

                default:
                    break;
            }
        }
    };

    private boolean check() {
        if (mUserNameText.getText().toString().trim().length() == 0) {
            showToast(R.string.name_null);
            return false;
        }

        if (mPwdText.getText().toString().trim().length() == 0) {
            showToast(R.string.pwd_null);
            return false;
        } else if (mPwdText.getText().toString().trim().length() < 6) {
            showToast(R.string.pwd_format);
            return false;
        }
        return true;
    }

    private RequestCallback mLoginCallback = new RequestCallback() {

        @Override
        public void onSuccess(String rawData, Object response) {
            LoginResponse loginResponse = (LoginResponse) response;

            String status = loginResponse.getStatus();
            String desc = loginResponse.getDesc();

            if (Constants.REQUEST_SUCCESS.equals(status)) {
                // Login success, need store the "sign" for other request.
                String loginSign = loginResponse.getSign();
                Preferences.saveLoginSign(LoginActivity.this, loginSign);
//            	 fix: 一次性commit
//                Editor editor = Preferences.getPreferences(LoginActivity.this).edit();
//            	editor.putString(Preferences.LOGIN_SIGN,  loginResponse.getSign());

                // We store the name/password but not while the user checked the
                // "auto login".
                // Because the name/password which login successfully is
                // available.
                String phoneNumber = mUserNameText.getText().toString();
                String password = mPwdText.getText().toString();
                Preferences.saveUserName(LoginActivity.this, phoneNumber);
                Preferences.savePassword(LoginActivity.this, password);
                Preferences.saveLoginStatus(LoginActivity.this, true);
//                editor.putString(Preferences.REMEMBERED_USERNAME,  phoneNumber);
//                editor.putString(Preferences.REMEMBERED_PWD,  password);
//                editor.putBoolean(Preferences.ISLOGIN, true);
//                editor.commit();
                MainActivity.launch(LoginActivity.this);
                finish();
            }
            else {
                Preferences.saveLoginSign(LoginActivity.this, "");
                Toast.makeText(LoginActivity.this, desc, Toast.LENGTH_LONG).show();
            }
            dismissDialog();

        }

        @Override
        public void onError(int statusCode, Throwable e, String rawData) {
            dismissDialog();
            if(NetworkUtils.isNetConnect(getApplicationContext())){
                showToast(R.string.oper_error);
            }else{
                showToast(R.string.net_error);
                 }
        }
    };

    protected void onActivityResult(int reqCode, int resultCode, Intent data) {
        if (reqCode == 0 && resultCode == RESULT_OK) {
            mPwdText.setText(Preferences.getPassword(this));
        }
    };

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), R.string.exit_app_tip,
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                DBLApplication.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
